<script setup>
import {Modal} from "bootstrap";
import {onBeforeUnmount, onMounted, ref} from "vue";
import GroupAvatarUpload from "@/components/svg/GroupAvatarUploadSvg.vue";
import {useUserStore} from "@/stores/userStore.js";
import router from "@/router/index.js";
import { useGroupStore } from "@/stores/groupStore.js";

import {showToast} from "@/components/toasts/LoginRegToast.js";
import {createGroup, joinGroup} from "@/api/group.js";
import emitter from "@/utils/EventBus.js";
const groupStore = useGroupStore()
const closeBtn = ref()
const previewImg = ref()
const isShowPreviewImg = ref(false)
const serverFormData = new FormData()
const groupName = ref()
const gpfp = ref(null)

const isCreating = ref(false)
const theModal = ref();
const previewIcon = (e) =>{
  previewImg.value.src = URL.createObjectURL(e.target.files[0])
  isShowPreviewImg.value = true
  gpfp.value = e.target.files[0]
}

onMounted(()=> {
  theModal.value = new Modal(document.getElementById('createServerModal'))
})

const groupLink = ref()

const joinRequest = async () => {
  const res = await joinGroup({gid: groupLink.value, uid: useUserStore().userInfo?.id})
  if (res.status === 200) {
    showToast('success','加入成功')
    emitter.emit('update groupList')
    closeBtn.value.click()
  }
}


const createGroupBtn = async () => {
  if (groupName.value === '' || groupName.value === undefined || groupName.value === null) {
    showToast('warning', '请输入名称！', '')
    return void 0
  }

  isCreating.value = true
  serverFormData.set('owner_id', useUserStore().userInfo?.id)
  serverFormData.set('group_name', groupName.value)
  serverFormData.set('group_pic', gpfp.value)

  const res = await createGroup(serverFormData)

  const newGroupUrl = ref()
  if(res.status === 200) {
    console.log(res.data)
    setTimeout(()=>{
      res.data[0].forEach(val => {
        groupStore.updateGroup({
          name: val.group_name,
          to: `/home/groupChat/${val.id}`,
          isDefault: false,
          icon: val.group_pic
        })
        newGroupUrl.value = `/home/groupChat/${val.id}`
      })
      theModal.value.hide()
      groupName.value = ''
      isCreating.value = false
      return router.replace(newGroupUrl.value)
    }, 2000)
  } else {
    console.error(res)
  }
}

onBeforeUnmount(()=> {
  closeBtn.value.click()
})
</script>

<template>
  <div class="modal fade" id="addServerModal" tabindex="-1" aria-labelledby="addServerModal" aria-hidden="true" data-mdb-backdrop="true" data-mdb-keyboard="true">
    <div class="modal-dialog modal-dialog-centered text-center d-flex justify-content-center">
      <div class="modal-content w-75">
        <div class="modal-header">
          <h5 class="modal-title" >创建你的群聊</h5>
          <button type="button" ref="closeBtn" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <p>创建一个群聊，和你的好友们能够畅聊！</p>
          <div class="mt-3">
            <button class="btn btn-sm btn-primary w-100 p-2" data-bs-target="#createServerModal" data-bs-toggle="modal">创建群聊</button>
          </div>
          <div class="mt-4">
            <h6 class="fw-bold">已有邀请链接？</h6>

            <div class="mb-3">
              <input type="text" class="form-control" v-model="groupLink"/>
            </div>

            <button class="btn btn-sm btn-secondary w-100 p-2" @click="joinRequest">加入群聊</button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="modal fade" id="createServerModal" tabindex="-1" aria-labelledby="createServerModal" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered d-flex justify-content-center">
      <div class="modal-content w-75">
        <div class="modal-header">
          <h5 class="modal-title">自定义群聊</h5>
          <button  type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body p-4">
          <form v-show="!isCreating">
            <div class="d-flex flex-column align-items-center">
              <label for="groupAvatar" style="cursor: pointer">
                <group-avatar-upload v-show="!isShowPreviewImg"/>
                <img v-show="isShowPreviewImg" id="previewImg" src="#" ref="previewImg" alt="你的资料">
              </label>
              <input class="file-input" @change="previewIcon" id="groupAvatar" type="file" tabindex="0" accept=".jpg,.jpeg,.png,.gif,.webp">
            </div>

            <div class="mt-3">
              <label class="form-label small fw-bold" for="groupName">群聊名称</label>
              <input type="text" id="groupName" v-model="groupName" class="form-control" />
            </div>
          </form>

          <h5 v-show="isCreating">正在创建 {{ groupName }}... </h5>
        </div>

        <div class="modal-footer">
          <button class="btn btn-sm btn btn-secondary" data-bs-target="#addServerModal" data-bs-toggle="modal">返回</button>
          <button class="btn btn-sm btn-primary" @click.prevent="createGroupBtn">确定</button>
        </div>

      </div>
    </div>
  </div>
</template>

<style scoped>
.file-input {
  display: none;
  font-size: 0;
}

#previewImg {
  display: block;
  margin: 0;
  padding: 0;
  border-radius: 50%;
  width: 80px;
  height: 80px;
}

.searchResult{
  transition: none;
}
.searchResult:hover {
  border-radius: 8px;
  background-color: rgba(129, 129, 129, 0.15);
}
</style>